import { useState, useEffect } from 'react';
import { toast } from 'sonner';
import AdminLayout from '@/components/admin/AdminLayout';
import ImageUpload from '@/components/common/ImageUpload';
import { cn } from '@/lib/utils';
import { useCompanyInfo, useUpdateCompanyInfo, useCreateCompanyInfo } from '@/hooks/useCompany';

// 公司信息数据类型定义
interface CompanyInfo {
  id?: number;
  company_name: string;
  company_logo?: string;
  about_us_image?: string;
  company_slogan: string;
  company_description: string;


  // 统计卡片字段
  stat1_title?: string;
  stat1_value?: string;
  stat2_title?: string;
  stat2_value?: string;
  stat3_title?: string;
  stat3_value?: string;
  stat4_title?: string;
  stat4_value?: string;

  company_introduction: string;
  created_at?: string;
  updated_at?: string;
}

// 默认公司信息
const getDefaultCompanyInfo = (): CompanyInfo => {
  return {
    company_name: '环境工程咨询有限公司',
    company_logo: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=environmental+engineering+company+logo%2C+clean+design%2C+blue+color&sign=c27ff3fa3e4891608ccffb2a9c777237',
    company_slogan: '专业环境工程咨询，守护绿色未来',
    company_description: '我公司成立于2000年，是一家集工程建设、设计、咨询、监理于一体的综合性环境工程企业。',

    // 统计卡片默认值
    stat1_title: '年行业经验',
    stat1_value: '25+',
    stat2_title: '完成项目',
    stat2_value: '500',
    stat3_title: '专业团队',
    stat3_value: '50-100人',
    stat4_title: '客户满意度',
    stat4_value: '100%',

    company_introduction: '我公司成立于2000年，是一家集工程建设、设计、咨询、监理于一体的综合性建筑企业。公司拥有各类专业技术人员300余人，其中高级职称人员50余人，中级职称人员150余人。多年来，公司始终坚持"质量第一、安全第一、信誉第一"的经营理念，先后完成了多项省市级重点工程，获得了社会各界的广泛好评。公司连续多年被评为"重合同守信用企业"、"AAA级信用企业"等荣誉称号。'
  };
};

export default function CompanyInfoManagement() {
  const [isEditing, setIsEditing] = useState(false);

  // 使用API hooks
  const { data: companyInfo, isLoading, error, refetch } = useCompanyInfo();
  const updateCompanyMutation = useUpdateCompanyInfo();
  const createCompanyMutation = useCreateCompanyInfo();

  // 表单状态
  const [formData, setFormData] = useState({
    company_name: '',
    company_slogan: '',
    company_description: '',
    company_introduction: '',

    // 统计卡片字段
    stat1_title: '',
    stat1_value: '',
    stat2_title: '',
    stat2_value: '',
    stat3_title: '',
    stat3_value: '',
    stat4_title: '',
    stat4_value: ''
  });
  
  // 处理输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  // 初始化表单数据
  useEffect(() => {
    if (companyInfo) {
      setFormData({
        company_name: companyInfo.company_name || '',
        company_slogan: companyInfo.company_slogan || '',
        company_description: companyInfo.company_description || '',
        company_introduction: companyInfo.company_introduction || '',

        // 统计卡片数据
        stat1_title: companyInfo.stat1_title || '年行业经验',
        stat1_value: companyInfo.stat1_value || '25+',
        stat2_title: companyInfo.stat2_title || '完成项目',
        stat2_value: companyInfo.stat2_value || '500',
        stat3_title: companyInfo.stat3_title || '专业团队',
        stat3_value: companyInfo.stat3_value || '50-100人',
        stat4_title: companyInfo.stat4_title || '客户满意度',
        stat4_value: companyInfo.stat4_value || '100%'
      });
    } else if (!isLoading && error) {
      // 如果没有数据且不是加载中，使用默认数据
      const defaultData = getDefaultCompanyInfo();
      setFormData({
        company_name: defaultData.company_name,
        company_slogan: defaultData.company_slogan,
        company_description: defaultData.company_description,
        company_introduction: defaultData.company_introduction,

        // 统计卡片默认数据
        stat1_title: defaultData.stat1_title || '年行业经验',
        stat1_value: defaultData.stat1_value || '25+',
        stat2_title: defaultData.stat2_title || '完成项目',
        stat2_value: defaultData.stat2_value || '500',
        stat3_title: defaultData.stat3_title || '专业团队',
        stat3_value: defaultData.stat3_value || '50-100人',
        stat4_title: defaultData.stat4_title || '客户满意度',
        stat4_value: defaultData.stat4_value || '100%'
      });
    }
  }, [companyInfo, isLoading, error]);
  
  // 切换编辑状态
  const toggleEdit = () => {
    setIsEditing(!isEditing);

    // 如果取消编辑，重置表单数据
    if (isEditing && companyInfo) {
      setFormData({
        company_name: companyInfo.company_name || '',
        company_slogan: companyInfo.company_slogan || '',
        company_description: companyInfo.company_description || '',
        company_introduction: companyInfo.company_introduction || '',

        // 统计卡片数据
        stat1_title: companyInfo.stat1_title || '年行业经验',
        stat1_value: companyInfo.stat1_value || '25+',
        stat2_title: companyInfo.stat2_title || '完成项目',
        stat2_value: companyInfo.stat2_value || '500',
        stat3_title: companyInfo.stat3_title || '专业团队',
        stat3_value: companyInfo.stat3_value || '50-100人',
        stat4_title: companyInfo.stat4_title || '客户满意度',
        stat4_value: companyInfo.stat4_value || '100%'
      });
    }
  };

  // 处理logo变化（包括上传和删除）
  const handleLogoChange = (url: string) => {
    if (companyInfo?.id) {
      // 如果已有公司信息，更新logo
      updateCompanyMutation.mutate(
        { company_logo: url },
        {
          onSuccess: () => {
            if (url) {
              toast.success('公司logo更新成功');
            } else {
              toast.success('公司logo已删除');
            }
            refetch(); // 重新获取数据
          },
          onError: (error: any) => {
            toast.error(error?.message || (url ? '更新logo失败' : '删除logo失败'));
          }
        }
      );
    } else {
      toast.error('请先保存公司基本信息');
    }
  };

  // 处理关于我们图片变化（包括上传和删除）
  const handleAboutUsImageChange = (url: string) => {
    if (companyInfo?.id) {
      // 如果已有公司信息，更新关于我们图片
      updateCompanyMutation.mutate(
        { about_us_image: url },
        {
          onSuccess: () => {
            if (url) {
              toast.success('关于我们图片更新成功');
            } else {
              toast.success('关于我们图片已删除');
            }
            refetch(); // 重新获取数据
          },
          onError: (error: any) => {
            toast.error(error?.message || (url ? '更新图片失败' : '删除图片失败'));
          }
        }
      );
    } else {
      toast.error('请先保存公司基本信息');
    }
  };

  // 处理logo上传错误
  const handleLogoUploadError = (error: string) => {
    toast.error(error);
  };

  // 处理关于我们图片上传错误
  const handleAboutUsImageUploadError = (error: string) => {
    toast.error(error);
  };
  
  // 保存公司信息
  const saveCompanyInfo = () => {
    // 验证必填字段
    if (!formData.company_name || !formData.company_slogan || !formData.company_description ||
        !formData.company_introduction) {
      toast.error('请填写所有必填字段');
      return;
    }

    const dataToSave = {
      company_name: formData.company_name,
      company_slogan: formData.company_slogan,
      company_description: formData.company_description,
      company_introduction: formData.company_introduction,

      // 统计卡片数据
      stat1_title: formData.stat1_title,
      stat1_value: formData.stat1_value,
      stat2_title: formData.stat2_title,
      stat2_value: formData.stat2_value,
      stat3_title: formData.stat3_title,
      stat3_value: formData.stat3_value,
      stat4_title: formData.stat4_title,
      stat4_value: formData.stat4_value
    };

    if (companyInfo?.id) {
      // 更新现有公司信息
      updateCompanyMutation.mutate(dataToSave, {
        onSuccess: () => {
          setIsEditing(false);
          toast.success('公司信息更新成功');
          refetch(); // 重新获取数据
        },
        onError: (error: any) => {
          toast.error(error?.message || '更新失败');
        }
      });
    } else {
      // 创建新的公司信息
      createCompanyMutation.mutate(dataToSave, {
        onSuccess: () => {
          setIsEditing(false);
          toast.success('公司信息创建成功');
          refetch(); // 重新获取数据
        },
        onError: (error: any) => {
          toast.error(error?.message || '创建失败');
        }
      });
    }
  };
  
  if (isLoading) {
    return (
      <AdminLayout>
        <div className="flex items-center justify-center min-h-[500px]">
          <div className="text-center">
            <i className="fa-solid fa-spinner fa-spin text-3xl text-blue-600 mb-4"></i>
            <p className="text-gray-600">加载中...</p>
          </div>
        </div>
      </AdminLayout>
    );
  }
  
  return (
    <AdminLayout>
      <div className="flex flex-col md:flex-row md:items-center md:justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-800">公司信息管理</h1>
          <p className="text-gray-600">管理公司基本信息和介绍内容</p>
        </div>
        <div className="flex space-x-3">
          {isEditing && (
            <button
              type="button"
              onClick={toggleEdit}
              className="mt-4 md:mt-0 font-medium py-2 px-4 rounded-lg transition-colors flex items-center bg-gray-100 hover:bg-gray-200 text-gray-700"
              disabled={updateCompanyMutation.isPending || createCompanyMutation.isPending}
            >
              <i className="fa-solid fa-times mr-2"></i> 取消编辑
            </button>
          )}
          <button
            type="button"
            onClick={isEditing ? saveCompanyInfo : toggleEdit}
            className={`mt-4 md:mt-0 font-medium py-2 px-4 rounded-lg transition-colors flex items-center ${
              isEditing
                ? 'bg-blue-600 hover:bg-blue-700 text-white'
                : 'bg-gray-100 hover:bg-gray-200 text-gray-700'
            }`}
            disabled={updateCompanyMutation.isPending || createCompanyMutation.isPending}
          >
            {updateCompanyMutation.isPending || createCompanyMutation.isPending ? (
              <>
                <i className="fa-solid fa-spinner fa-spin mr-2"></i> 保存中...
              </>
            ) : isEditing ? (
              <>
                <i className="fa-solid fa-save mr-2"></i> 保存信息
              </>
            ) : (
              <>
                <i className="fa-solid fa-edit mr-2"></i> 编辑信息
              </>
            )}
          </button>
        </div>
      </div>
      
      {/* 公司信息卡片 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden mb-8">
        <div className="p-6 border-b">
          <div className="flex flex-col md:flex-row md:items-center">
            <div className="flex items-center mb-4 md:mb-0">
              {isEditing ? (
                <div className="mr-4">
                  <ImageUpload
                    value={companyInfo?.company_logo || ''}
                    onChange={handleLogoChange}
                    onError={handleLogoUploadError}
                    width={64}
                    height={64}
                    maxSize={2}
                    placeholder="上传Logo"
                    autoCompress={true}
                  />
                </div>
              ) : (
                <div className="w-16 h-16 rounded-lg overflow-hidden mr-4 border-2 border-gray-100">
                  <img
                    src={companyInfo?.company_logo || '/images/default-logo.png'}
                    alt={companyInfo?.company_name || '公司Logo'}
                    className="w-full h-full object-contain"
                  />
                </div>
              )}
              <div className="flex-1">
                {isEditing ? (
                  <div className="space-y-3">
                    <input
                      type="text"
                      name="company_name"
                      value={formData.company_name}
                      onChange={handleInputChange}
                      className="w-full text-xl font-bold px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                      placeholder="请输入公司名称"
                    />
                    <input
                      type="text"
                      name="company_slogan"
                      value={formData.company_slogan}
                      onChange={handleInputChange}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                      placeholder="请输入公司标语"
                    />
                  </div>
                ) : (
                  <div>
                    <h2 className="text-xl font-bold text-gray-800">{companyInfo?.company_name || '公司名称'}</h2>
                    <p className="text-gray-600">{companyInfo?.company_slogan || '公司标语'}</p>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
        
        <div className="p-6">


          {/* 首页统计卡片编辑区域 */}
          <div className="mb-8">
            <h3 className="text-lg font-semibold text-gray-800 mb-3">首页统计卡片</h3>
            <p className="text-sm text-gray-600 mb-4">这些数据将显示在首页"关于我们"部分的统计卡片中</p>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {/* 统计卡片1 */}
              <div className="bg-blue-50 p-4 rounded-lg border border-blue-100">
                <div className="mb-3">
                  <label className="block text-sm font-medium text-gray-700 mb-1">卡片1标题</label>
                  {isEditing ? (
                    <input
                      type="text"
                      name="stat1_title"
                      value={formData.stat1_title}
                      onChange={handleInputChange}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors bg-white"
                      placeholder="如：年行业经验"
                    />
                  ) : (
                    <p className="text-gray-800 font-medium">{companyInfo?.stat1_title || '年行业经验'}</p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">卡片1数值</label>
                  {isEditing ? (
                    <input
                      type="text"
                      name="stat1_value"
                      value={formData.stat1_value}
                      onChange={handleInputChange}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors bg-white"
                      placeholder="如：25+"
                    />
                  ) : (
                    <p className="text-2xl font-bold text-blue-600">{companyInfo?.stat1_value || '25+'}</p>
                  )}
                </div>
              </div>

              {/* 统计卡片2 */}
              <div className="bg-green-50 p-4 rounded-lg border border-green-100">
                <div className="mb-3">
                  <label className="block text-sm font-medium text-gray-700 mb-1">卡片2标题</label>
                  {isEditing ? (
                    <input
                      type="text"
                      name="stat2_title"
                      value={formData.stat2_title}
                      onChange={handleInputChange}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors bg-white"
                      placeholder="如：完成项目"
                    />
                  ) : (
                    <p className="text-gray-800 font-medium">{companyInfo?.stat2_title || '完成项目'}</p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">卡片2数值</label>
                  {isEditing ? (
                    <input
                      type="text"
                      name="stat2_value"
                      value={formData.stat2_value}
                      onChange={handleInputChange}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors bg-white"
                      placeholder="如：500"
                    />
                  ) : (
                    <p className="text-2xl font-bold text-green-600">{companyInfo?.stat2_value || '500'}</p>
                  )}
                </div>
              </div>

              {/* 统计卡片3 */}
              <div className="bg-purple-50 p-4 rounded-lg border border-purple-100">
                <div className="mb-3">
                  <label className="block text-sm font-medium text-gray-700 mb-1">卡片3标题</label>
                  {isEditing ? (
                    <input
                      type="text"
                      name="stat3_title"
                      value={formData.stat3_title}
                      onChange={handleInputChange}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors bg-white"
                      placeholder="如：专业团队"
                    />
                  ) : (
                    <p className="text-gray-800 font-medium">{companyInfo?.stat3_title || '专业团队'}</p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">卡片3数值</label>
                  {isEditing ? (
                    <input
                      type="text"
                      name="stat3_value"
                      value={formData.stat3_value}
                      onChange={handleInputChange}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors bg-white"
                      placeholder="如：50-100人"
                    />
                  ) : (
                    <p className="text-2xl font-bold text-purple-600">{companyInfo?.stat3_value || '50-100人'}</p>
                  )}
                </div>
              </div>

              {/* 统计卡片4 */}
              <div className="bg-orange-50 p-4 rounded-lg border border-orange-100">
                <div className="mb-3">
                  <label className="block text-sm font-medium text-gray-700 mb-1">卡片4标题</label>
                  {isEditing ? (
                    <input
                      type="text"
                      name="stat4_title"
                      value={formData.stat4_title}
                      onChange={handleInputChange}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors bg-white"
                      placeholder="如：客户满意度"
                    />
                  ) : (
                    <p className="text-gray-800 font-medium">{companyInfo?.stat4_title || '客户满意度'}</p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">卡片4数值</label>
                  {isEditing ? (
                    <input
                      type="text"
                      name="stat4_value"
                      value={formData.stat4_value}
                      onChange={handleInputChange}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors bg-white"
                      placeholder="如：100%"
                    />
                  ) : (
                    <p className="text-2xl font-bold text-orange-600">{companyInfo?.stat4_value || '100%'}</p>
                  )}
                </div>
              </div>
            </div>
          </div>

          {/* 关于我们图片编辑区域 */}
          <div className="mb-8">
            <h3 className="text-lg font-semibold text-gray-800 mb-3">关于我们页面图片</h3>
            <p className="text-sm text-gray-600 mb-4">这张图片将显示在首页"关于我们"部分的右侧</p>
            <div className="bg-gray-50 p-6 rounded-lg border border-gray-200">
              {isEditing ? (
                <div className="space-y-4">
                  <ImageUpload
                    value={companyInfo?.about_us_image || ''}
                    onChange={handleAboutUsImageChange}
                    onError={handleAboutUsImageUploadError}
                    width={400}
                    height={300}
                    maxSize={5}
                    placeholder="上传关于我们图片"
                    autoCompress={true}
                  />
                  <p className="text-xs text-gray-500">
                    推荐尺寸：800x600像素，支持JPG、PNG格式，最大5MB
                  </p>
                </div>
              ) : (
                <div className="flex items-center justify-center">
                  {companyInfo?.about_us_image ? (
                    <img
                      src={companyInfo.about_us_image}
                      alt="关于我们"
                      className="max-w-full max-h-64 object-contain rounded-lg border border-gray-300"
                      onError={(e) => {
                        const target = e.target as HTMLImageElement;
                        target.src = '';
                      }}
                    />
                  ) : (
                    <div className="w-full h-64 bg-gray-200 rounded-lg flex items-center justify-center border-2 border-dashed border-gray-300">
                      <div className="text-center">
                        <i className="fa-solid fa-image text-4xl text-gray-400 mb-2"></i>
                        <p className="text-gray-500">暂无图片</p>
                      </div>
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>

          <div className="mb-8">
            <h3 className="text-lg font-semibold text-gray-800 mb-3">公司简介</h3>
            {isEditing ? (
              <textarea
                name="company_description"
                value={formData.company_description}
                onChange={handleInputChange}
                rows={3}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                placeholder="请输入公司简介"
              ></textarea>
            ) : (
              <p className="text-gray-600 leading-relaxed">{companyInfo?.company_description || '公司简介'}</p>
            )}
          </div>

          <div className="mb-8">
            <h3 className="text-lg font-semibold text-gray-800 mb-3">公司介绍</h3>
            {isEditing ? (
              <textarea
                name="company_introduction"
                value={formData.company_introduction}
                onChange={handleInputChange}
                rows={6}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                placeholder="请输入公司详细介绍"
              ></textarea>
            ) : (
              <div className="text-gray-600 leading-relaxed whitespace-pre-wrap">
                {companyInfo?.company_introduction || '公司详细介绍'}
              </div>
            )}
          </div>



          {companyInfo?.updated_at && (
            <div className="text-sm text-gray-500 italic text-right">
              最后更新时间: {new Date(companyInfo.updated_at).toLocaleDateString('zh-CN')}
            </div>
          )}
        </div>
      </div>
      
      {!isEditing && (
        <div className="bg-blue-50 border border-blue-100 rounded-xl p-6">
          <h3 className="text-lg font-semibold text-blue-800 mb-3 flex items-center">
            <i className="fa-solid fa-info-circle mr-2"></i> 编辑提示
          </h3>
          <p className="text-blue-700">
            点击"编辑信息"按钮可以修改公司信息。修改后的信息将实时更新到网站前台展示。
          </p>
        </div>
      )}
    </AdminLayout>
  );
}
